from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import users
from mako.template import Template
from mako.lookup import TemplateLookup

from models.project import MasterControlProject, MasterControlSubProject
from utilities import GetToken, GetProject, GetMemberList
import random, sys


class AddSubprojectHandler(webapp.RequestHandler):
    def get(self, mcp_code):
        mcp = MasterControlProject.get_by_key_name(mcp_code)
        if mcp:
            members = GetMemberList(mcp.pivotal_project_id, mcp.token)
        else:
            members = None
        return self.__view(members = members, project = mcp)
        
    def post(self, mcp_code):
        mcp = MasterControlProject.get_by_key_name(mcp_code)
        if mcp:
            members = GetMemberList(mcp.pivotal_project_id, mcp.token)
        else:
            members = None
        project_id = self.request.POST.get('project_id', '')
        errors = []
        if not project_id:
            errors.append('Pivotal Project ID is required.')
        try:
            project_id = int(project_id)
        except:
            errors.append('Pivotal Project ID must be an integer.')
        label = self.request.POST.get('label', '').lower()
        if not label:
            errors.append('Team Name is required.')
        integration_name = self.request.POST.get('integration_name')
        if not integration_name:
            errors.append('Integration name is requred.')
        owner = self.request.POST.get('owner', '')
        if not owner:
            errors.append('Story Owner is required.')
        token = self.request.POST.get('token', '')
        username = self.request.POST.get('pivotal_username', '')
        password = self.request.POST.get('pivotal_password', '')
        if not token and username and password:
            token = GetToken(username, password)
            if not token:
                errors.append('Username or password are incorrect.')
            else:
                username = ''
                password = ''
        if not token and (username or password):
            errors.append('Username and password must be supplied together.')
        
        if errors:
            return self.__view(members = members, errors = errors, project_id = project_id, label = label, integration_name = integration_name, owner = owner, token = token, username = username)
        
        project = GetProject(project_id, token or mcp.token)
        if project:
            name = project.getElementsByTagName('name')[0].firstChild.data.strip()
        else:
            errors.append('User associated with token does not have access to project %s' % (project_id, ))
            return self.__view(members = members, errors = errors, project_id = project_id, label = label, integration_name = integration_name, owner = owner, token = token, username = username)
        
        try:
            if MasterControlProject.all().filter('pivotal_project_id =', project_id).get() or MasterControlSubProject.all().filter('pivotal_project_id =', project_id).get():
                errors.append('Cannot create a MasterControl project with Pivotal Project ID %d as it is already used in MasterControl' % (project_id, ))
                return self.__view(members = members, errors = errors, project_id = project_id, label = label, integration_name = integration_name, owner = owner, token = token, username = username)
            
            mcsp = MasterControlSubProject(master_project = mcp, pivotal_project_id = project_id, name = name, token = token, integration_name = integration_name, label = label, owning_user_name = owner)
            mcsp.put()
            self.redirect('/secure/%s/' % (mcp.key().id_or_name()))
            return
        except Exception, e:
            errors.append('Unable to save project information. %s' % (e.message,))
            return self.__view(members = members, errors = errors, project_id = project_id, label = label, integration_name = integration_name, owner = owner, token = token, username = username)
        
        
            
    def __view(self, **kwargs):
        temp = Template(filename = 'templates/add_subproject.html', lookup = TemplateLookup(directories=['.']))
        self.response.out.write(temp.render(**kwargs))